const fs = require('fs');
const fileService = require("../service/file.service")
const userService = require("../service/user.service")
const { AVATAR_PATH } = require('../constans/file-path')
const { APP_HOST, APP_PORT } = require('../app/config')

class FileController {
    async uploadAvatar(ctx, next) {
        const { filename, mimetype, size } = ctx.req.file;
        const { id } = ctx.user;
        // 2.将图像信息数据保存到数据库中
        const result = await fileService.createAvatar(filename, mimetype, size, id);
        // 3.将图片地址保存到user表中
        const avatarUrl = `${APP_HOST}:${APP_PORT}/users/${id}/avatar`;
        await userService.updateAvatarUrlById(avatarUrl, id);

        ctx.body = '上传成功'
    }
    async updateAvatar(ctx, next) {
        const { avatarId } = ctx.params
        const { filename, mimetype, size } = ctx.req.file;
        const { filename: filenamePre } = await fileService.getAvatarById(avatarId)
        fs.unlink(`${AVATAR_PATH}/${filenamePre}`, (err) => {
            if (err) {
                console.log(err);
                return;
            }
            console.log('删除原头像文件成功')
        })
        const result = await fileService.updateAvatar(filename, mimetype, size, avatarId);
        ctx.body = '更新成功'
    }
    async savePictureInfo(ctx, next) {
        const { files } = ctx.req
        const { id } = ctx.user
        const { momentId } = ctx.query;
        for (const file of files) {
            const { filename, mimetype, size } = file
            await fileService.createPicture(filename, mimetype, size, id, momentId);
        }
        ctx.body = '动态上传图片成功'
    }
}

module.exports = new FileController()